﻿public static partial class Utility
{

    /// <summary>
    /// 枚举工具
    /// </summary>
    public static class Enum
    {

        /// <summary>
        /// 字符串转枚举
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str"></param>
        /// <returns></returns>
        public static T ToEnum<T>(string str)
        {
            try
            {
                return (T)System.Enum.Parse(typeof(T), str);
            }
            catch
            {
                return default;
            }
        }
        /// <summary>
        /// 字符串转枚举
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="val"></param>
        /// <returns></returns>
        public static T ToEnum<T>(int val, T defaultVal)
        {
            try
            {
                return (T)System.Enum.ToObject(typeof(T), val);
            }
            catch
            {
                return defaultVal;
            }
        }

        /// <summary>
        /// 字符串转枚举
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str"></param>
        /// <returns></returns>
        public static void TryToEnum<T>(string str, out object result)
        {
            System.Enum.TryParse(typeof(T), str, out result);
        }

        /// <summary>
        /// 获取枚举长度
        /// </summary>
        /// <typeparam name="T">枚举长度</typeparam>
        /// <returns></returns>
        public static int Count<T>() where T : struct, System.Enum
        {
            return System.Enum.GetValues(typeof(T)).Length;
        }
    }
}
